package com.yugu.encrypt;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.yugu.util.StringUtils;

/**
 * AES加解密操作类
 */
@SuppressWarnings("restriction")
public class AESOperator {
    /**
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    public static final String skey = "smkldospd121daaa";
    /**
     * 偏移量,可自行修改
     */
    private static String ivParameter = "1016449182184177";

    private static AESOperator instance = null;

    private AESOperator() {

    }

    public static AESOperator getInstance() {
        if (instance == null) {
            instance = new AESOperator();
        }
        return instance;
    }

    public String Encrypt(String encData, String secretKey, String vector) throws Exception {

        if (secretKey == null) {
            return null;
        }
        if (secretKey.length() != 16) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
        // 此处使用BASE64做转码。
        return new BASE64Encoder().encode(encrypted);
    }

    /**
     * 加密
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public String encrypt(String sSrc, String sKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        // 此处使用BASE64做转码。
        String replace = replace(new BASE64Encoder().encode(encrypted));
        //再将BASE64转16位进制字符串
        return encodeHex(replace);
    }

    /**
     * 解密
     *
     * @param sSrc
     * @param sKey
     * @return
     */
    public String decrypt(String sSrc, String sKey) {
        try {
            //先转化为字符串
            String s = decodeHex(sSrc);
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(s);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    public String Decrypt(String sSrc, String key, String ivs) {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }
        return strBuf.toString();
    }

    /**
     * 去除 换行符、制表符
     *
     * @param str
     * @return
     */
    public static String replace(String str) {
        if (!StringUtils.isEmpty(str)) {
            return str.replaceAll("\r|\n", "");
        }
        return str;
    }
    /**
     * 字符串转十六进制字符串
     *
     * @author guxf
     * @param str 源字符串
     * @return 十六进制字符串
     * */
    public  String encodeHex(String str) {
        // 定义变量保存结果
        final StringBuffer hexStr = new StringBuffer();
        // 遍历字符串，直接使用Integer.toHexString返回每个字符的十六进制字符串
        for (int i = 0; i < str.length(); i++)
            hexStr.append(Integer.toHexString(str.charAt(i)));
        // 返回结果
        return hexStr.toString();
    }
    /**
     * 十六进制字符串转字符串
     *
     * @author guxf
     * @param hexStr 原16进制字符串
     * @return 字符串
     * */
    public String decodeHex(String hexStr) {
        // 定义字符数组，用于保存字符串字符，长度为16进制字符串的一半
        byte[] strs = new byte[hexStr.length() / 2];
        // 遍历赋值
        for (int i = 0; i < strs.length; i++) {
            // 截取高位，使用Integer.parseInt进行转换
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            // 截取低位，使用Integer.parseInt进行转换
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            // 拼接赋值
            strs[i] = (byte)(high * 16 + low);
        }
        // 将字符数组转换为字符串，返回结果
        return new String(strs);
    }

    //测试
    public static void main(String[] args) throws Exception {
        // 需要加密的字串
//        String cSrc = "{\"loginName\":\"master\",\"secret\":\"123456\"}";
        String cSrc = "a2";
        System.out.println(cSrc);
        // 加密
        String enString = AESOperator.getInstance().encrypt(cSrc, skey);
        System.out.println("加密后的字串是：" + replace(enString));
        String test = replace(enString);

        // 解密
        String DeString = AESOperator.getInstance().decrypt(test, skey);
        System.out.println("解密后的字串是：" + DeString);
    }

}
